一、全局前置beforeEach
- return true // 或者不寫return,意思一樣,順利跳轉
- return { name: 'Login' } // 重新導向,會再次執行router.beforeEach
- return false // 中斷導航
二、全局後置beforeEach
router.afterEach((to, from) => {
// 函式內寫程式碼
})
和beforeEach不同,afterEach不會在函式內return任何東西,也沒有next()
router.beforeEach((to, from) => {
if (to.name === 'Dashboard' && !isLoggedIn()) {
return { name: 'Login' }
}
})
router.afterEach((to, from) => {
console.log('afterEach 執行!')
})
假設有一段邏輯
「我要進入dashboard,但因無權限,被重新導向login頁」
它會這樣執行:
上述邏輯,beforeEach共執行2次,afterEach只會執行1次
三、路由獨享守衛
寫在路由表上
const routes = [
{
path: '/users/:id',
component: UserDetails,
beforeEnter: (to, from) => {
// reject the navigation
return false
},
},
]
當網址params, query, hash改變時,不會觸發beforeEnter。
如果嵌套路由時,beforeEnter位在父路由,共同子路由list, details移動時,不觸發路由。
const routes = [
{
path: '/user',
beforeEnter() {
// ...
},
children: [
{ path: 'list', component: UserList },
{ path: 'details', component: UserDetails },
],
},
]